在這一章中,我們將介紹 EVM 中的環境和區塊資訊指令。
# These opcodes seem to belong in the environment block,
# but we are out of opcode space in 0x3*
CHAINID = 0x46
SELFBALANCE = 0x47
BASEFEE = 0x48
#
# Block Information
#
BLOCKHASH = 0x40
COINBASE = 0x41
TIMESTAMP = 0x42
NUMBER = 0x43
DIFFICULTY = 0x44
PREVRANDAO = 0x44 # EIP-4399: supplant DIFFICULTY with PREVRANDAO
GASLIMIT = 0x45
先來創建一個Block
類別,它可以隨機生成區塊需要的數據:
import random
import time
class Block:
def __init__(self):
self.blockhash = self._generate_hash()
self.coinbase = self._generate_address()
self.timestamp = int(time.time()) # 獲取當前時間戳
self.number = random.randint(1, 20000000) # 隨機生成區塊編號
self.prevrandao = self._generate_hash()
self.gaslimit = random.randint(10, 50)
self.chainid = 1
self.selfbalance = random.randint(50, 150)
self.basefee = random.randint(10, 50)
def _generate_hash(self):
return "0x" + "".join(random.choice("0123456789abcdef") for _ in range(64))
def _generate_address(self):
return "0x" + "".join(random.choice("0123456789abcdef") for _ in range(40))
def to_dict(self):
return {
"blockhash": self.blockhash,
"coinbase": self.coinbase,
"timestamp": self.timestamp,
"number": self.number,
"prevrandao": self.prevrandao,
"gaslimit": self.gaslimit,
"chainid": self.chainid,
"selfbalance": self.selfbalance,
"basefee": self.basefee,
}
這個 Block
類別有兩個私有方法:_generate_hash
和 _generate_address
,用於隨機生成雜湊和地址。to_dict
方法將 Block
對象的屬性轉換為字典格式,以便於打印和使用。
當您運行上述代碼時,它將隨機生成一個新的區塊數據並打印出來。您可以根據需要進行調整。
def chainid(self):
self.evm.stack.append(self.evm.chainid)
def selfbalance(self):
self.evm.stack.append(self.evm.get_balance(self.evm.address))
def basefee(self):
self.evm.stack.append(self.evm.basefee)
def blockhash(self):
block_number = self.evm.stack.pop()
hash_value = self.evm.get_blockhash(block_number)
self.evm.stack.append(hash_value)
def coinbase(self):
self.evm.stack.append(self.evm.coinbase)
def timestamp(self):
self.evm.stack.append(self.evm.timestamp)
def number(self):
self.evm.stack.append(self.evm.block_number)
def difficulty(self):
self.evm.stack.append(self.evm.difficulty)
def prevrandao(self):
self.evm.stack.append(self.evm.prevrandao)
def gaslimit(self):
self.evm.stack.append(self.evm.gaslimit)